package com.wsz.security.service.impl;

import com.wsz.security.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

@Component
@RequiredArgsConstructor
public class UserDetailsServerImpl implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.wsz.security.pojo.User user = userService.getUserByUserName(username);

        if(user == null){
            throw new UsernameNotFoundException("该用户不存在");
        }

        System.out.println(user.getPassword()+username);
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();// simple 简单的  Granted 赋予 Authority 权限
        user.getRoles().forEach( role -> authorities.add(new SimpleGrantedAuthority(role.getName())));
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
